/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/9/29 12:29
 */
package com.gitee.mechanic.mybatis.base;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 扩展 Mybatis plus ServiceImpl 实现，并增加自定义的公共接口实现。
 *
 * @author mechanic
 */
@Slf4j
public class SuperServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements SuperService<T> {

    @Override
    public List<T> selectList() {
        return baseMapper.selectList(getEmptyWrapper());
    }

    @Override
    public List<T> selectList(Wrapper<T> wrapper) {
        return baseMapper.selectList(getWrapper(wrapper));
    }

    public Page<T> selectPage(int pageNum){
        Page<T> page = new Page<>();
        page.setCurrent(pageNum);
        EntityWrapper<T> wrapper = new EntityWrapper<>();
        SqlHelper.fillWrapper(page, wrapper);
        page.setRecords(baseMapper.selectPage(page, wrapper));
        return page;
    }

    @Override
    public Page<T> selectPage(Wrapper<T> wrapper, int pageNum) {
        Page<T> page = new Page<>();
        page.setCurrent(pageNum);
        SqlHelper.fillWrapper(page, wrapper);
        page.setRecords(baseMapper.selectPage(page, wrapper));
        return page;
    }

    protected Wrapper<T> getEmptyWrapper() {
        return new EntityWrapper<>();
    }

    private Wrapper<T> getWrapper(Wrapper<T> wrapper) {
        return SqlHelper.isEmptyOfWrapper(wrapper) ? new EntityWrapper<>() : wrapper;
    }
}
